package com.example.stray_animal_management_system.controller;

import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    /** 🧩 获取个人信息 */
    @GetMapping("/{userId}")
    public Map<String, Object> getUserInfo(@PathVariable Integer userId) {
        Map<String, Object> res = new HashMap<>();
        User user = userService.getById(userId);
        if(user == null) {
            res.put("code", 404);
            res.put("msg", "用户不存在");
            return res;
        }

        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", user);
        return res;
    }

    /**
     *  修改个人信息
     *  */
    @PutMapping("/update")
    public Map<String, Object> updateUserInfo(@RequestBody Map<String, Object> payload) {
        Map<String, Object> res = new HashMap<>();

        Integer userId = (Integer) payload.get("id");
        User dbUser = userService.getById(userId);
        if (dbUser == null) {
            res.put("code", 404);
            res.put("msg", "用户不存在");
            return res;
        }

        // 校验昵称唯一性
        if (payload.containsKey("nickname")) {
            String nickname = (String) payload.get("nickname");
            if (nickname == null || !nickname.matches("^[a-zA-Z0-9\u4e00-\u9fa5]{2,16}$")) {
                res.put("code", 400);
                res.put("msg", "昵称格式不合法（2~16位，可包含中文、英文或数字）");
                return res;
            }
            // 检查是否有其他用户使用相同昵称
            User sameNickname = userService.lambdaQuery()
                    .eq(User::getNickname, nickname)
                    .ne(User::getId, userId)
                    .one();
            if (sameNickname != null) {
                res.put("code", 400);
                res.put("msg", "昵称已被占用");
                return res;
            }
            dbUser.setNickname(nickname);
        }

        // 校验邮箱唯一性
        if (payload.containsKey("email")) {
            String email = (String) payload.get("email");
            if (email != null && !email.isEmpty()) {
                if (!email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
                    res.put("code", 400);
                    res.put("msg", "邮箱格式不正确");
                    return res;
                }
                User sameEmail = userService.lambdaQuery()
                        .eq(User::getEmail, email)
                        .ne(User::getId, userId)
                        .one();
                if (sameEmail != null) {
                    res.put("code", 400);
                    res.put("msg", "该邮箱已被使用");
                    return res;
                }
                dbUser.setEmail(email);
            }
        }

        // 校验手机号唯一性
        if (payload.containsKey("phone")) {
            String phone = (String) payload.get("phone");
            if (phone != null && !phone.isEmpty()) {
                if (!phone.matches("^1[3-9]\\d{9}$")) {
                    res.put("code", 400);
                    res.put("msg", "手机号格式不正确");
                    return res;
                }
                User samePhone = userService.lambdaQuery()
                        .eq(User::getPhone, phone)
                        .ne(User::getId, userId)
                        .one();
                if (samePhone != null) {
                    res.put("code", 400);
                    res.put("msg", "该手机号已被使用");
                    return res;
                }
                dbUser.setPhone(phone);
            }
        }

        // 头像（可为空）
        if (payload.containsKey("avatar")) {
            dbUser.setAvatar((String) payload.get("avatar"));
        }

        // 修改密码逻辑
        String oldPassword = (String) payload.get("oldPassword");
        String newPassword = (String) payload.get("newPassword");

        if (newPassword != null && !newPassword.isEmpty()) {
            if (oldPassword == null || !oldPassword.equals(dbUser.getPassword())) {
                res.put("code", 400);
                res.put("msg", "原密码错误，无法修改密码");
                return res;
            }
            if (newPassword.length() < 6 || newPassword.length() > 20) {
                res.put("code", 400);
                res.put("msg", "新密码长度必须为6~20位");
                return res;
            }
            dbUser.setPassword(newPassword);
        }

        userService.updateById(dbUser);

        res.put("code", 200);
        res.put("msg", "更新成功");
        res.put("data", dbUser);
        return res;
    }

    // 上传头像
    @PostMapping("/uploadAvatar")
    public Map<String, Object> uploadAvatar(@RequestParam("file") MultipartFile file,
                                            @RequestParam("userId") Integer userId) throws IOException {
        Map<String, Object> res = new HashMap<>();

        // 上传目录：项目根路径 + /uploads/avatars/
        String uploadDir = System.getProperty("user.dir") + "/uploads/avatars/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 必须确保目录存在
        }

        // 文件名
        String fileName = "avatar_" + userId + "_" + System.currentTimeMillis() + ".jpg";

        // 保存文件
        File dest = new File(uploadDir + fileName);
        file.transferTo(dest); // 这里使用绝对路径

        // 更新用户头像路径（前端访问用 /uploads/avatars/...）
        User user = userService.getById(userId);
        user.setAvatar("http://localhost:8080/uploads/avatars/" + fileName);
        userService.updateById(user);

        res.put("code", 200);
        res.put("msg", "上传成功");
        res.put("url", user.getAvatar());
        return res;
    }
    /**
     * 用户注销账号
     * @param userId 用户ID
     * @param password 用户密码
     * @return 操作结果
     */
    @DeleteMapping("/selfdelete")
    public Map<String, Object> userLogout(@RequestParam("userId") Long userId,
                                          @RequestParam("password") String password) {
        Map<String, Object> res = new HashMap<>();

        // 根据 userId 获取用户
        User user = userService.getById(userId);

        if (user == null) {
            res.put("code", 404);
            res.put("msg", "用户不存在");
            return res;
        }

        // 校验密码（可以使用 BCrypt 进行密码校验）
        if (!userService.checkPassword(user, password)) {
            res.put("code", 403);
            res.put("msg", "密码错误");
            return res;
        }

        // 删除用户（可以选择删除用户记录或者禁用用户账号）
        userService.removeById(userId);

        res.put("code", 200);
        res.put("msg", "账号已成功注销");
        return res;
    }



}


